/**
 * AbstractServer.java created by zhangzhidong 
 * at 下午10:23:03 2015年9月8日
 */
package fileserver;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;

/**
 * @author Alex
 *
 */
public abstract class AbstractServer implements Server {
	private int port = -1;
	private ServerSocketChannel ssc;
	protected Selector  selector;
	public AbstractServer(){}
	
	public void init() {
		if(port==-1){
			throw new RuntimeException("Port can't be null");
		}
		if(ssc==null){
			try {
				ssc = ServerSocketChannel.open();
				if(selector ==null)
					selector =  Selector.open();
				ssc.configureBlocking(false);
				ssc.register(this.selector, SelectionKey.OP_ACCEPT);
				System.out.println("start server on prot"+this.port);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				System.out.println(e.getMessage());
			}
			
		}
		try {
			ssc.socket().bind(new InetSocketAddress(this.port));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println(e.getMessage());
		}
		initInternal();
	}
	public abstract void initInternal();
	public final void setPort(int port){
		this.port=port;
	}
	public final void stop(){
		try {
			stopInternal();
			ssc.close();		
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println(e.getMessage());
		}
	}
	public abstract void stopInternal()	;
			
	
}
